$(document).ready(function () {
    layui.use('form', function () {
        var form = layui.form;
        form.render();

        getFloorPlan();

        // 监听输入框
        $("#houseHouseholdDiv>div>div>input").bind("input propertychange", function() {
            onSelectChange();
        });

        // 监听Select
        form.on("select(selectFilter)", function(data) {
            $("input[name='householdId']").val(data.value);
        });

        // 监听Select
        form.on("select(selectFilter2)", function(data) {
            $("#floorPlanId").val(data.value);
            getFloorPlanImg(data.value);
        });

    });
});

function addHouse() {

    var formJSON = $("#house-submit-form").serializeObject();

    // 添加住户
    ajax(
        "/admin/house/addHouse", "POST",
        formJSON, true, true, true
    ).done(function () {
        loadingPage("/admin/house/house");;
    });

}

function onSelectChange() {
    var householdName = $("#houseHouseholdDiv>div>div>input").val();
    ajax(
        "/admin/house/getHousehold", "POST",
        { householdName: householdName }
        ,false, true, false
    ).done(function (returnData) {
        if (returnData.length > 0) {

            var select = $("#houseHouseholdName");
            select.empty();
            select.append("<option value=''>搜索住户</option>");

            for (var i = 0; i < returnData.length; i ++) {
                select.append("<option value='" + returnData[i].householdId + "'>" + returnData[i].householdName + "(" + returnData[i].householdNo + ")</option>");
            }

            form.render('select');
            reloadSelectListener();
        }


    });
}

function getFloorPlan() {

    ajax(
        "/admin/house/getFloorPlan", "POST",
        null,true, true, false
    ).done(function (returnData) {

        var select = $("#houseFloorPlanName");
        select.empty();
        select.append("<option value=''>点击选择户型</option>");

        for (var i = 0; i < returnData.length; i ++) {
            select.append("<option value='" + returnData[i].houseFloorPlanId + "'>" + returnData[i].houseFloorPlanName + "</option>");
        }

        form.render('select');
        reloadSelectListener();
    });

}

function getFloorPlanImg(id) {

    ajax(
        "/admin/floorplan/getFloorPlan", "POST",
        { houseFloorPlanId: id }
        ,true, true, false
    ).done(function (returnData) {

        $("#img-header").attr("src", "data:image/jpg;base64," + returnData.houseFloorPlanFileBase64);

    });

}

function reloadSelectListener() {

    // 监听输入框
    $("#houseHouseholdDiv>div>div>input").bind("input propertychange", function() {
        onSelectChange();
    });

}